package com.fixme4trade.business;

import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.security.SecurityContext;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;

import com.fixme4trade.constant.Role;
import com.fixme4trade.domain.Customer;
import com.fixme4trade.domain.Product;
import com.fixme4trade.domain.Seller;
import com.fixme4trade.domain.User;
import com.fixme4trade.persistence.UserDAO;

@BusinessController
@ApplicationScoped
public class UserBC extends DelegateCrud<User, Long, UserDAO> {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private Logger logger;
	
	@Inject
    private MessageContext messageContext;
	
	@Inject
	//private Provider<CustomerBC> p_customerBC;
	private CustomerBC customerBC;
	
	@Inject
	//private Provider<SellerBC> p_sellerBC;
	private SellerBC sellerBC;
	
	@Inject
	private SecurityContext securityContext;
	
	/*
	public UserBC() {
		customerBC = p_customerBC.get();
		sellerBC = p_sellerBC.get();		
	}
	*/
	
	@Override
	public void insert(User user) {		
		super.insert(user);
		
		List <Role> roles = user.getRoleList();
		for(Role role : roles) {
			if (role == Role.CUSTOMER) {
				Customer customer = new Customer();
				
				customer.setUser(user);
				
				customerBC.insert(customer);
			}
			if (role == Role.SELLER) {
				Seller seller = new Seller();
				
				seller.setUser(user);
				
				sellerBC.insert(seller);
			}
		}
	}

	@Override
	public void update(User user) {
		super.update(user);
	}

	@Override
	public void delete(Long id) {
		super.delete(id);
	}

	public boolean checkUsernamePassword(String username, String password) {				
		return getDelegate().checkUsernamePassword(username, password);
	}

	public Object getUserByUsername(String username) {		
		return getDelegate().getUserByUsername(username);
	}

	public Seller getAuthenticatedSeller() {
		User user = (User)securityContext.getUser();			
		
		return sellerBC.getSellerByUser(user);
	}
	
	public Customer getAuthenticatedCustomer() {
		User user = (User)securityContext.getUser();			
		
		return customerBC.getCustomerByUser(user);
	}
}
